package com.xyzwps.harbor.handler.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

import java.util.Optional;

@Component
public final class LogFilter implements HandlerFilterFunction<ServerResponse, ServerResponse> {

    @Override
    public Mono<ServerResponse> filter(ServerRequest req, HandlerFunction<ServerResponse> next) {
        var reqDesc = req.methodName() + " " + req.path();
        log.info("{} is incoming", reqDesc);

        return next.handle(req)
                .map(resp -> {
                    if (resp instanceof EntityResponse) {
                        var entity = ((EntityResponse<?>) resp).entity();
                        if (entity instanceof Optional) {
                            var $entity = (Optional<?>) entity;
                            if ($entity.isEmpty()) {
                                log.info("{} response nothing", reqDesc);
                            } else {
                                log.info("{} response {}", reqDesc, $entity.get()); // TODO: json stringify
                            }
                        } else {
                            log.info("{} response {}", reqDesc, entity); // TODO: json stringify
                        }
                    } else {
                        log.info("{} response done", reqDesc);
                    }
                    return resp;
                });
    }

    private static final Logger log = LoggerFactory.getLogger(LogFilter.class);
}
